package httpUtils

import (
	"fmt"
	"net/http"
)

type ResultDataAble interface {
	WriterSucceedResponse(w http.ResponseWriter)
	WriterErrorResponse(w http.ResponseWriter, errorMessage string, debugMessage string)
	SucceedMessage(data interface{})
	ErrorMessage(message, debugMessage string)

	Error() string
}
type AppHandleFuncErr func(w http.ResponseWriter, r *http.Request, resultDataAble ResultDataAble) error

func AppHandleFunc(appHandle AppHandleFuncErr, resultDataAble ResultDataAble) func(http.ResponseWriter, *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		defer func() {
			i := recover()
			if i != nil {
				handleData(w, resultDataAble, i)
			}
		}()
		err := appHandle(w, r, resultDataAble)
		handleData(w, resultDataAble, err)
	}
}
func handleData(w http.ResponseWriter, resultDataAble ResultDataAble, i interface{}) {
	if resultData, ok := i.(ResultDataAble); ok {
		resultData.WriterSucceedResponse(w)
	} else if err, ok := i.(error); ok {
		resultDataAble.WriterErrorResponse(w, "服务器内部错误", fmt.Sprintf("%v", err))
	}
}
